import '@ant-design/compatible/assets/index.css';
import { Card, Button, message, Modal, Descriptions, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import { connect } from 'dva';
import Ellipsis from '../../../components/Ellipsis';
import React, { PureComponent } from 'react';
import styles from './style.less';
import { getToken, getMd5, downloadFileByUrl } from '@/utils/utils';
import { windowUrl } from '../../../../public/global';
import { getOptAuthHeaders } from '@/utils/common';

const mapStateToProps = (state: any) => ({
  dataPermission: state.menu.dataPermission,
  electricFenceMng: state.electricFenceMng,
  loading: state.loading.effects['electricFenceMng/getVehicleList'],
});
class RelateVehicleAdd extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      formData: {},
      typeOptions: [], //车型
      dealerCode: sessionStorage.getItem('dealerCode'),
      orgId: sessionStorage.getItem('fenceOrgId'),
      selectedRowKeys: [],
      uploadVisible: false,
      templateFileUrl: null,
      fileList: [],
      importBtnLoading: false,
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    const { dispatch } = this.props;
    this.handleFlushPage();
    dispatch({
      type: 'electricFenceMng/getData',
      payload: { url: '/common/template/detail', templateCode: 'electricFenceBindVin' },
      callback: (res: any) => {
        this.setState({ templateFileUrl: res.data?.templateUrl });
      },
    });
  }
  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { formValues, dealerCode, orgId } = this.state;
    const params = {
      ...formValues,
      dealerCode,
      orgId,
    };
    dispatch({
      type: 'electricFenceMng/getVehicleList',
      payload: { url: '/mscreditbusiness/vehicle/credit/dealer/page', ...params },
    });
  };
  //根据车系code查询车型
  handleGetVehicleTypeList = seriesCode => {
    if (seriesCode) {
      const {
        dataPermission: { BRAND = [] },
      } = this.props;
      this.props.dispatch({
        type: 'http/getDataWithRes',
        payload: {
          url: '/msdevice/base/vehicle/type/list',
          seriesCode,
          brandId: BRAND[0],
        },
        callback: response => {
          if (response && response.statusCode == '0') {
            this.setState({
              typeOptions: response.data || [],
            });
          } else {
            this.setState({
              typeOptions: [],
            });
            message.error(response.statusMessage);
          }
        },
      });
    } else {
      this.setState({
        typeOptions: [],
      });
    }
  };
  close = () => {
    const { closeModal } = this.props;
    closeModal(false);
  };
  save = () => {
    const { selectedRowKeys } = this.state;
    const { closeModal } = this.props;
    const fenceId = sessionStorage.getItem('fenceId');
    if (selectedRowKeys.length > 0) {
      this.props.dispatch({
        type: 'http/postObj',
        payload: {
          url: `/credit/vehicle/fence/bathBind?id=${fenceId}&operatorType=0`,
          vinList: selectedRowKeys,
        },
        callback: response => {
          // if (response && response.statusCode == '0') {
          message.success('操作成功');
          //  this.handleTableData();
          closeModal(true);
          // } else {
          //   message.error(response.statusMessage);
          // }
        },
      });
    } else {
      message.warning('请选择关联车辆');
    }
  };
  import = () => {};
  handleFileChange = (info: any) => {
    this.setState({
      filePath: '',
      fileList: [],
    });
    let { fileList, file } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'uploading') {
      this.setState({
        fileList: [...fileList],
      });
    } else if (
      file.status === 'done' &&
      file.response &&
      file.response.responseCode == '200' &&
      file.response.fileRecordList
    ) {
      message.success(`${file.name} 上传成功`);
      this.setState({
        filePath: info.file.response.fileRecordList[0].fileUri,
        fileList: fileList,
      });
    } else if (file.status === 'done' && file.response && file.response.statusCode !== '0') {
      message.error(file.response.statusMessage);
      return;
    } else if (file.status === 'error') {
      message.error(`${file.name} 上传失败`);
      return;
    } else if (file.status === 'removed') {
      return;
    }
  };
  handleSubmit = () => {
    const { filePath, orgId } = this.state;
    if (!filePath.trim()) {
      message.warning('请上传文件');
      return;
    }
    this.setState({
      importBtnLoading: true,
    });
    this.props.dispatch({
      type: 'electricFenceMng/postObjWithRes',
      payload: {
        url: '/credit/vehicle/fence/importTask',
        filePath,
        fenceId: sessionStorage.getItem('fenceId'),
        orgId,
      },
      callback: (response: { statusCode: string }) => {
        if (response && response.statusCode == '0') {
          message.success('操作成功,请点击[任务中心]按钮查看处理进度!');
          this.setState({ uploadVisible: false });
        } else {
          // message.error(response.statusMessage);
        }
        this.setState({
          importBtnLoading: false,
        });
      },
    });
  };
  render() {
    const {
      formValues,
      typeOptions,
      dealerCode,
      orgId,
      selectedRowKeys,
      uploadVisible,
      templateFileUrl,
      fileList,
      importBtnLoading,
    } = this.state;
    const {
      electricFenceMng: {
        vehicleData: { rows, pagination },
      },
      loading,
      modalVisible,
      seriesOptions,
    } = this.props;

    const url = `${windowUrl}/upload/single?bizType=m18`;
    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" loading={loading} onClick={this.save} type="primary">
          保存
        </Button>
      </div>
    );
    const columns = [
      { title: 'VIN', dataIndex: 'vin' },
      {
        title: '品牌',
        dataIndex: 'brandName',
      },
      {
        title: '车系',
        dataIndex: 'seriesName',
        render: text => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '车型',
        dataIndex: 'styleName',
        render: text => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const tableProps = {
      columns,
      dataSource: rows,
      loading,
      rowKey: (record: any) => record.vin,
      pagination: paginationProps,
      rowSelection: {
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.setState({
            selectedRowKeys: selectedRowKeys,
          });
        },
      },
      scroll: { x: 'max-content' },
    };
    const searchItems = [
      {
        type: 'input',
        title: 'VIN',
        key: 'vin',
      },
      {
        type: 'select',
        title: '车系',
        key: 'seriesCode',
        selectOptions: seriesOptions,
        keyValue: ['seriesCode', 'seriesName'],
        onChange: this.handleGetVehicleTypeList,
      },
      {
        title: '车型',
        type: 'select',
        selectOptions: typeOptions,
        key: 'styleCode',
        keyValue: ['typeCode', 'typeName'],
      },
    ];

    return (
      <Modal
        style={{ top: 20 }}
        width={800}
        footer={footer}
        title="新增关联车辆"
        visible={modalVisible}
        onCancel={this.close}
      >
        <Card bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{
              type: 'electricFenceMng/getVehicleList',
              url: '/mscreditbusiness/vehicle/credit/dealer/page',
            }}
            extraArgs={{ dealerCode: dealerCode, orgId, bindFlag: 0 }}
            saveFormValues={(val: any) => {
              return this.setState({ formValues: Object.assign(formValues, val) });
            }}
            handleFormReset={() => this.setState({ formValues: {}, typeOptions: [] })}
          />
        </Card>
        <Card className={styles.standardTable} bordered={false}>
          <div className="my_newItem">
            <Button
              size="small"
              type="primary"
              onClick={() => this.setState({ uploadVisible: true })}
            >
              批量导入
            </Button>
          </div>

          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{
              type: 'electricFenceMng/getVehicleList',
              url: '/mscreditbusiness/vehicle/credit/dealer/page',
              extraArgs: { dealerCode: dealerCode, orgId, bindFlag: 0 },
            }}
            formValues={formValues}
            currentName="curPage"
          />
        </Card>
        <Modal
          title="批量导入"
          width={950}
          visible={uploadVisible}
          okButtonProps={{ size: 'small' }}
          cancelButtonProps={{ size: 'small' }}
          onCancel={() => this.setState({ uploadVisible: false })}
          footer={[
            <Button
              loading={importBtnLoading}
              key="confirm"
              type="primary"
              size="small"
              disabled={fileList.length === 0}
              onClick={this.handleSubmit}
            >
              确认
            </Button>,
          ]}
        >
          <Descriptions column={1} style={{ paddingTop: 10, paddingLeft: 8 }}>
            <Descriptions.Item label="模板">
              {/* {templateFileUrl ? (
                <a href={templateFileUrl} title="点击下载模板文件">
                  下载
                </a>
              ) : (
                '暂无模板文件'
              )} */}
              {templateFileUrl ? (
                <a
                  onClick={() => {
                    downloadFileByUrl(templateFileUrl, '批量导入关联车辆.xlsx');
                  }}
                >
                  点击下载模板文件
                </a>
              ) : (
                '暂无模板文件'
              )}
            </Descriptions.Item>
            <Descriptions.Item label="选择文件">
              <Upload
                action={url}
                headers={{
                  OptAuthorization: `${getToken()}`,
                  ...getOptAuthHeaders(),
                  shaSign: getMd5('bizType=m18'),
                }}
                className={styles.uploadFile}
                accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,.xls,.xlsx,application/vnd.ms-excel"
                fileList={fileList}
                multiple={false}
                onChange={this.handleFileChange}
              >
                <Button size="small" icon={<UploadOutlined />} type="primary">
                  导入
                </Button>
              </Upload>
            </Descriptions.Item>
          </Descriptions>
        </Modal>
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(RelateVehicleAdd);
